package sit.mycatalog.ejb.sess;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import sit.mycatalog.ejb.dao.CatnodeDao;
import sit.mycatalog.ejb.dao.ItemDao;
import sit.mycatalog.jpa.Catnode;
import sit.mycatalog.util.AbstractSess;

/**
 * Session Bean implementation class CatnodeSess
 */
@Stateless
@LocalBean
public class CatnodeSess extends AbstractSess {
	@EJB
	private CatnodeDao m_daoCatnode;
	@EJB
	private ItemDao m_daoItem;
	
	public Catnode getCatnode(Integer p_intCatid) throws Exception {
		return m_daoCatnode.findByPrimaryKey(p_intCatid);
	}
	
	public List<Catnode> getByParent(Integer p_intParentid) throws Exception {
		return m_daoCatnode.findByParent(p_intParentid); 
	}
	
	public Catnode getAllChild(Catnode p_entCatnode) throws Exception {
		return m_daoCatnode.findAllChild(p_entCatnode);
	}
	
	public List<Catnode> getAll() throws Exception {
		return m_daoCatnode.findAll();
	}
	
	public List<Catnode> getAllExcept(Integer p_intCatid) throws Exception {
		return m_daoCatnode.findAllExcept(p_intCatid);
	}
	
	public boolean createCatnode(Catnode p_catnode) throws Exception {
		return m_daoCatnode.create(p_catnode);
	}
	
	public boolean updateCatnode(Catnode p_catnode) throws Exception {
		boolean complete = false;
		
		try {
			Catnode catnode = m_daoCatnode.findByPrimaryKey(p_catnode.getCatid());
			
			if(catnode.isCheck()) {
				catnode.setName(p_catnode.getName());
				catnode.setCattype(p_catnode.getCattype());
				catnode.setParentid(p_catnode.getParentid());
				
				complete = true;
			}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
		
		return complete;
	}
	
	public boolean deleteCatnode(Integer p_catid) throws Exception {
		if(m_daoItem.findByCatid(p_catid).size() > 0) {
			return false;
		} else {
			return m_daoCatnode.remove(p_catid);
		}
    }
	
	public List<Catnode> getNodeOnly() throws Exception {
		return m_daoCatnode.findByCattype("N");
	}
}
